<template>
  <div>
    看日志就可以了
  </div>
</template>

<script>
/* eslint-disable */
import { 
  mnemonicGenerate,
  cryptoWaitReady,
  decodeAddress, 
  signatureVerify
} from '@polkadot/util-crypto';
import keyring from '@polkadot/ui-keyring';
import { ApiPromise, WsProvider } from '@polkadot/api';
import { u8aToHex } from '@polkadot/util';
import { addressToEvm } from '@polkadot/util-crypto';
import axios from 'axios'
import qs from 'qs'
export default {
  name: 'Main',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      mnemonic_word: '',

    }
  },
  components:{

  }, mounted: function () {
    var mnemonic = this.CreateMnemonic()
    var password = 'myStr0ngP@ssworD'
    console.log("等待初始化")
    var self = this
    this.GetBalance("5GeMxhXb2hoeoNJuR3rCheAivjh1391y5GLLQK5drsicUAw5", (obj)=>{console.log("获取余额", obj)})
    this.GetMemberNftCount("5GeMxhXb2hoeoNJuR3rCheAivjh1391y5GLLQK5drsicUAw5", (obj)=>{console.log("获取NFT总数", obj)})
    this.InitKeyStore().then(function () {
      /*
      console.log("生成助记词:", mnemonic)
      console.log("保存助记词:", self.SaveAccount("default", password, mnemonic))
      console.log("获取账户地址:", self.GetAccountAddress("default"))
      console.log("备份账户JSON:",self.GetAccountBackupJson("default", password))
      // 转账测试， 由于需要账户上有钱，所以先设置账户为一个有钱的账户
      self.SaveAccount("default", password, 'garden door trophy glove nice better current bubble fan dynamic donkey slush')
      self.Transaction(
        "default", 
        password, 
        '5DUbUtvMjGGehsjUHxrC9fUww8KsrubKtjnLejLA8xkCAeeP', 
        20000, 
        (tx)=> console.log("转账成功，tx为:",tx), 
        (error)=>console.log("转账失败，错误为:",error))
      */
      
      //self.GetUser('default', password)
      //console.log("start login")
      //self.Login('default', password)
    })
  }, methods: {
    // 初始化账户功能，返回promise
    InitKeyStore: async function () {
      await cryptoWaitReady()
      keyring.loadAll({ ss58Format: 42, type: 'sr25519' })
    },
    // 创建助记词
    CreateMnemonic: function () {
      return mnemonicGenerate(12)
    },
    // 保存账户信息
    SaveAccount: function (name, password, mnemonic) {
      // remove same name
      var address_list = []
      keyring.getAccounts().forEach(({ address, meta, publicKey }) => {
        if (meta['name'] === name) {
          address_list.push(address)
        }
      })
      address_list.forEach((address) => {
        keyring.forgetAccount(address)
      })
      const { pair, json } = keyring.addUri(mnemonic, password, { name: name })
      return json
    },
    // 获取账户地址
    GetAccountAddress: function(name) {
      var rtn = null
      keyring.getAccounts().forEach(({ address, meta, publicKey }) =>{
        if (meta['name'] === name) {
          rtn = address
        }
      })
      return rtn
    },
    // 备份账户，返回json。（保存到硬盘，这块前端实现）
    GetAccountBackupJson: function (name, password) {
      var pair = keyring.getPair(this.GetAccountAddress(name))
      return keyring.backupAccount(pair, password)
    },
    // 转账
    // from_account_name：账户名称
    // password: 账户密码
    // to_address: 要转账到的账户
    // amount: 转账金额
    // OKCB(x): 转账成功回调，x为tx
    // ErrorCB(x): 转账失败回调，x为错误
    Transaction: async function (from_account_name, password, to_address, amount, OkCB, ErrorCB){
      var wsProvider = new WsProvider('wss://dotdev.eieichina.com/wss'); // 这个是rpc地址，需要根据实际修改
      var api = await ApiPromise.create({ provider: wsProvider });
      var pair = keyring.getPair(this.GetAccountAddress(from_account_name));
      pair.unlock(password)
      const txHash = await api.tx.balances
      .transfer(to_address, amount*10000000000)
      .signAndSend(pair, ({ status, events }) => {
          // 首先监听错误
          var error_str = ''
          events.filter(({ event }) =>
            api.events.system.ExtrinsicFailed.is(event)
          ).forEach(({ event: { data: [error, info] } }) => {
              if (error.isModule) {
                const decoded = api.registry.findMetaError(error.asModule);
                const { documentation, method, section } = decoded;
                error_str = method + ':' + section;
              } else {
                error_str = error.toString();
              }
          });
          if ( error_str != '' ){ // 若发生错误
            txHash();
            ErrorCB(error_str)
          } else if (status.isFinalized) { // 若无错误最终确认
            OkCB(status.hash.toHex())
          }
      }).catch((error) => {
          ErrorCB(error)
          console.log("发生错误")
      });

      // Show the hash
      console.log(`Submitted with hash ${txHash}`);
    },
    // 获取账户余额
    // address: 要获取的账户地址
    // 返回值:{
    //   bigint:  以12345676809n这种方式表示的数字
    //   human: 以 12345 BML这种方式表示的数字 
    // }
    GetBalance: async function (address, OkCB){
      var wsProvider = new WsProvider('wss://dotdev.eieichina.com/wss'); // 这个是rpc地址，需要根据实际修改
      var api = await ApiPromise.create({ provider: wsProvider });
      const unsub = await api.query.system.account(address, (balance) => {
            console.log(`The balances are ${balance.nonce}`);
            console.log(balance.toHuman())
            console.log("balance:", balance.data.free.toHuman())
            OkCB(balance.data.free.toString())
      });
    },
    // 获取会员nft的总数
    GetMemberNftCount: async function (address, OkCB){
      var wsProvider = new WsProvider('wss://dotdev.eieichina.com/wss'); // 这个是rpc地址，需要根据实际修改
      var api = await ApiPromise.create({ provider: wsProvider });
      const unsub = await api.query.nft.balanceCount(address, 1, (balance) => {
            console.log(`The nft balances are`, balance.toString());
            OkCB(balance.toString())
      });
    },
    // 获取会员nft的总数
    GetMemberNftCount: async function (address, OkCB){
      var wsProvider = new WsProvider('wss://dotdev.eieichina.com/wss'); // 这个是rpc地址，需要根据实际修改
      var api = await ApiPromise.create({ provider: wsProvider });
      const unsub = await api.query.nft.balanceCount(address, 1, (balance) => {
            console.log(`The nft balances are`, balance.toString());
            OkCB(balance.toString())
      });
    },
    // 获取权益nft的总数
    GetMemberNftCount: async function (address, OkCB){
      var wsProvider = new WsProvider('wss://dotdev.eieichina.com/wss'); // 这个是rpc地址，需要根据实际修改
      var api = await ApiPromise.create({ provider: wsProvider });
      const unsub = await api.query.nft.balanceCount(address, 2, (balance) => {
            console.log(`The nft balances are`, balance.toString());
            OkCB(balance.toString())
      });
    },
    // 进行登录
    Login: function(account_name, password){
      var msg = {
        address: this.GetAccountAddress(account_name),
        timestamp: Date.parse(new Date())// 精确到秒的时间
      }
      var pair = keyring.getPair(this.GetAccountAddress(account_name));
      pair.unlock(password)
      msg["sign"] = u8aToHex(pair.sign(JSON.stringify(msg)))
      axios.post('/api/login',
       msg
      ).then(function (data) {
        console.log("登录成功:", data)
      }).catch(function (error) {
        console.log("登录失败:", error)
      })
      // this.verify(msg)
    },
    verify: function(msg){
        const msg_addr = msg.address
        const msg_timestamp = msg.timestamp
        const msg_sign = msg.sign;
        const publicKey = decodeAddress(msg_addr);
        const hexPublicKey = u8aToHex(publicKey);
        console.log("pubKey:", msg_addr, hexPublicKey)
        console.log(JSON.stringify({address:msg_addr, timestamp:msg_timestamp}))
        console.log("verify:", signatureVerify(JSON.stringify({address:msg_addr, timestamp:msg_timestamp}), msg_sign, hexPublicKey).isValid)
    },
    GetAuthMsg: function(account_name, password) {
      var msg = {
        address: this.GetAccountAddress(account_name),
        timestamp: Date.parse(new Date())// 精确到秒的时间
      }
      var pair = keyring.getPair(this.GetAccountAddress(account_name));
      pair.unlock(password)
      msg["sign"] = u8aToHex(pair.sign(JSON.stringify(msg)))
      return msg
    },
    GetUser: function (account_name, password) {
      var msg = this.GetAuthMsg(account_name, password)
      axios.post('/api/users/',
       qs.stringify(msg)
      ).then(function (data) {
        console.log(data)
      }).catch(function (error) {
        console.log(error)
      })
    }
  }
}
</script>
